import { createRouter, createWebHistory } from 'vue-router'
import axios from 'axios'
import Home from '@/components/Home.vue'
import Download from '@/components/Download.vue'
import Login from '@/components/Login.vue'
import We from '@/components/We.vue'

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    {
        path: '/we',
        name: 'We',
        component: We,
        meta: { requiresAuth: true }
    },
    {
        path: '/download',
        name: 'Download',
        component: Download,
    },
    {
        path: '/login',
        name: 'Login',
        component: Login
    },
]

const router = createRouter({
    history: createWebHistory(),
    routes: routes
})

async function Authenticated() {
    try {
        const response = await axios.get('http://localhost:5000/authenticate', {
            headers: { "Access-Control-Allow-Origin": "*" },
            withCredentials: true
        });
        console.log(response.data);
        return response.data.status === 200;
    } catch (error) {
        console.error('Error checking login status:', error);
        return false;
    }
}

router.beforeEach(async (to, from, next) => {
    if (to.meta.requiresAuth) {
        // 需要鉴权才能访问
        const authenticated = await Authenticated()
        if (authenticated) {
            // 鉴权成功，跳转
            next();
        } else {
            // 鉴权失败，跳转到登录界面
            next('/login');
        }
    } else {
        // 不需要鉴权
        next();
    }
})

export default router

